package com.credithc.eagleeye.api.web;
import com.credithc.eagleeye.api.factory.ESFactory;
import com.credithc.eagleeye.api.vo.AlertLogVo;
import com.credithc.framework.es.util.ElasticSearchUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.List;
/**
 * 描 述: <br/>
 * 作 者: zhangjin<br/>
 * 创 建：2018年02月07日<br/>
 * 版 本：v1.0.0<br>
 * <p>
 * 历 史: (版本) 作者 时间 注释 <br/>
 */
@SuppressWarnings("Duplicates")
@Slf4j
@Controller
public class AlertApiCtrl extends BaseApiCtrl {
    private final static String EAGLE_ALERT_LOG_ES_INDEX = ".eagle-alert-log";
    private final static String EAGLE_ALERT_LOG_ES_TYPE = "log";

    @RequestMapping(value = "/alertInfo", method = {RequestMethod.GET})
    public void queryTraceInfo(HttpServletRequest request, HttpServletResponse response) {
        try {
            String alertId = request.getParameter("id");
            response.setCharacterEncoding("UTF-8");
            response.setHeader("Content-Type", "text/html;charset=utf-8");
            PrintWriter out = response.getWriter();
            if(StringUtils.isNotBlank(alertId)) {
                ElasticSearchUtil elasticSearchUtil = ESFactory.getInstance();
                BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
                boolQueryBuilder.must(QueryBuilders.matchPhraseQuery("alertId", alertId));
                List<AlertLogVo> list = elasticSearchUtil.search(AlertLogVo.class, EAGLE_ALERT_LOG_ES_INDEX, EAGLE_ALERT_LOG_ES_TYPE, boolQueryBuilder);
                if (list != null && list.size() > 0) {
                    AlertLogVo alertLogVo = list.get(0);
                    out.print(alertLogVo.getTitle()+"<br>"+StringUtils.replace(alertLogVo.getMessage(),"\n","<br>"));
                }
            }else{
                out.print("未找到报警信息");
            }
            out.flush();
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
